package models

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
)

/**
 * @Author: zhaobin
 * @Description 对cookie操作的封装
 * @Date: 2022-05-18 17:46
 */

type ginCookie struct{}

// Cookie 实例化结构体
var Cookie = &ginCookie{}

const (
	CartList = "cartList"
)

// Set 往cookie中写入数据的方法
func (cookie ginCookie) Set(c *gin.Context, key string, value interface{}) {
	bytes, _ := json.Marshal(value)
	c.SetCookie(key, string(bytes), 3600*24*30, "/", c.Request.Host, false, true)
}

// Get 获取cookie中数据的方法
func (cookie ginCookie) Get(c *gin.Context, key string, obj interface{}) bool {

	valueStr, err1 := c.Cookie(key)
	if err1 == nil && valueStr != "" && valueStr != "[]" {
		err2 := json.Unmarshal([]byte(valueStr), obj)
		return err2 == nil
	}
	return false
}

// Remove 移除cookie中的数据
func (cookie ginCookie) Remove(c *gin.Context, key string) bool {
	c.SetCookie(key, "", -1, "/", c.Request.Host, false, true)
	return true
}
